import {Toast} from 'antd-mobile';

const msgTime = G.msgTime;

export default function apiInfo(data, showError) {
	let info;
	if (data.then) {
		info = data;
	} else {
		const {url = G.path.api, ...reqData} = data;
		info = fetch(url, {
			method: 'post',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			body:JSON.stringify(reqData),
            //     JSON.stringify({
            //     'Identity':{
            //         "serviceCode":"lushang",
            //         "appCode":"lushang_app1",
            //         "identityName":"ls_user_1",
            //         "identityKey":"333cb962ac59075asdfb07152d234b91",
            //         "sign":"7b8a9fa92b0c3e70728ccd0194bd4888"
            //     }
            // }),
            // JSON.stringify(reqData),
			credentials: 'include'
		});
	}

	return new Promise(function(resolve, reject) {
		info.then((res) => res.json()).then((res) => {
			res = res || {
				errno: -1,
				errmsg: '请求失败，请重试！'
			};

			if (res.errno === 0) {
				resolve(res.data);
			} else {
				showError !== false && Toast.fail(res.errmsg, msgTime);

				if (res.errno === 401) { //session失效
					//setTimeout(function() {
					//	location.href = bis.path.login + '?ref=' + encodeURIComponent(location.href);
					//}, 2000);
					res.errmsg = '未登录或登录过期';
				}

				let err = new Error(res.errmsg);
				err.errno = res.errno;
				err.errmsg = res.errmsg;

				reject(err);
			}
		}).catch((err) => {
			Toast.fail('网络异常，请重试！', msgTime);

			reject(err);
		});
	});
}
